<template>
    <transition name="el-fade-in-linear">
    <div class="officialAccount" v-show="isShow">
        <div class="mainBox">
            <img class="closeBtn" @click="closeBtn" src="../assets/img/closeBtn.png" alt="">
            <div class="infoBox">
                <div class="name">微信公众号</div>
            </div>
            <div class="codeBox">
                <div class="code">
                    <img :src="deviceQrcode" alt="">
                </div>
            </div>
            <div class="tips">
                <div>您先扫码关注微信公众号，</div>
                <div>点击菜单栏【我要取片】，获取您的照片~</div>
            </div>
        </div>
    </div>
    </transition>
</template>

<script>
import {getDeviceQrcode} from '../server/api'
import {mapState} from 'vuex'
import { EventSourcePolyfill } from "event-source-polyfill";
export default {
    props:{
        // 是否展示
        isShow:false,
    },
    computed:{
        ...mapState([
            //必须带引号
            'token'
        ])
    },
    data(){
        return {
            deviceQrcode:'',
        }
    },
    watch:{
        isShow(newVal,oldVal){
            if(newVal == true){
                // 获取公众号二维码
                this.getDeviceQrcodes()
                // 判断是否关注了公众号
                this.followInterestFun();
            }
        }
    },
    methods:{
        closeBtn(){
            this.$emit('update:isShow',false);
        },
        // 是否关注了公众号
        followInterestFun(){
            this.sseConnect()
            // setTimeout(() => {
            //     this.$emit('update:isShow',false)
            //     this.$emit('scanCodeEnd')
            // }, 2000);
        },
        // 获取公众号二维码
        getDeviceQrcodes(){
            let deviceCode = localStorage.getItem('deviceCode');
            getDeviceQrcode(deviceCode,'orderNo').then(res=>{
                console.log(res);
                this.deviceQrcode = res.data.deviceQrcode
            }).catch(err=>{
                console.log(err);
            })
        },
        sseConnect(){
            let that = this;
            let webSocketIp = localStorage.getItem('webSocketIp');
            let clientId = localStorage.getItem('clientId');
            let deviceCode = localStorage.getItem('deviceCode');
            const url = process.env.VUE_APP_BASE_API+'/resource/sse/device/'+deviceCode  //'https://localhost:6601/sse'

            const eventSource = new EventSourcePolyfill(
                url,
                {
                    headers: {
                        Authorization:'Bearer '+this.token,  // 你想通过 EventSource 请求发送的自定义头信息
                        clientId,
                    },
                }
            );
            /*
            * open：订阅成功（和后端连接成功）
            */
            eventSource.onopen = function (e) {
                console.log(e, "连接刚打开时触发");
            };
            /*
            * message：后端返回信息，格式可以和后端协商
            */

            eventSource.onmessage = function (e) {
                console.log(e,'后端返回信息，格式可以和后端协商');
                if(e.data){
                    // 关注成功
                    // 关闭链接
                    eventSource.close();
                    that.$emit('update:isShow',false)
                    that.$emit('scanCodeEnd')
                }
                // const data = JSON.parse(e.data) || {};//这里后端返回的是字符串所以目前我这边有转换
            };
            /*
            * error：错误（可能是断开，可能是后端返回的信息）
            */
            eventSource.onerror = function (e) {
                console.log(e, "连接无法打开时触发");
                eventSource.close(); // 关闭连接
                    setTimeout(() => {
                }, 5000);
            };


            // const sse=new EventSource(url,{
            //     headers: {
            //         Authorization:'Bearer'+this.token,  // 你想通过 EventSource 请求发送的自定义头信息
            //         clientId,
            //         deviceCode
            //     }
            // });
            // sse.addEventListener("open",(e)=>{
            //     //sse open
            //     $eventBus.emit('SseOpenEvent')
            // })
            // sse.addEventListener("message",({data})=>{
            //     //收到消息
            //     console.log('message',data)
            //     const d=JSON.parse(data);
            //     $eventBus.emit("receiveMsgEvent",data)
            // })
            // sse.addEventListener('error',(err)=>{
            //     //报错
            //     console.log('err '+JSON.stringify(err));
            // })
        },
        
    },
}
</script>

<style lang="less" scoped>
.officialAccount{
    width: 100%;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.5);
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    .mainBox{
        width: 760px;
        height: 960px;
        margin: 0 auto;
        margin-top: 396px;
        background-image: url('../assets/img/propImg.png');
        background-size: 100% 960px;
        position: relative;
        padding-top: 140px;
        box-sizing: border-box;
        padding-right: 20px;
        .closeBtn{
            width: 86px;
            height: 83px;
            position: absolute;
            right: -41px;
            top: -42px;
        }
        .infoBox{
            width: 100%;
            height: auto;
            text-align: center;
            .name{
                font-size: 48px;
                color: #000000;
                font-weight: bold;
            }
        }
        .codeBox{
            width: 400px;
            height: 400px;
            background-image: url('../assets/img/Rectangle 30399.png');
            background-size: 100% 400px;
            margin: 0 auto;
            margin-top: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            .code{
                width: 340px;
                height: 340px;
                background-color: #fff;
                img{
                    width: 100%;
                    height: 100%;
                }
            }
        }
        .tips{
            width: 100%;
            font-size: 32px;
            color: #000000;
            text-align: center;
            margin-top: 26px;
            font-weight: bold;
        }
    }
}
</style>